import { ctx2, docMgr } from '@app-cad/module';
import { useEffect } from 'react';

export const useSwitchVisibility = (
  base?: string | string[],
  shape?: string,
) => {
  useEffect(() => {
    if (!base || !shape) {
      return () => {};
    }

    const baseArray = Array.isArray(base) ? base : [base];
    const baseOriginallyVisible = baseArray.map(
      (id) => docMgr.getDocumentObjectById(id)?.visibility,
    );

    baseArray.forEach((id, index) => {
      if (!baseOriginallyVisible[index]) {
        ctx2.commandCenters.basicCommands.setVisibility(id, true);
      }
    });
    const shapeOriginallyVisible =
      docMgr.getDocumentObjectById(shape)?.visibility;
    ctx2.commandCenters.basicCommands.setVisibility(shape, false);

    ctx2.viewer.requestRender();

    return () => {
      baseArray.forEach((id, index) => {
        if (!baseOriginallyVisible[index]) {
          ctx2.commandCenters.basicCommands.setVisibility(id, false);
        }
      });
      if (shapeOriginallyVisible) {
        ctx2.commandCenters.basicCommands.setVisibility(shape, true);
      }

      ctx2.viewer.requestRender();
    };
  }, [base, shape]);
};
